/**
 * 鱼塘界面
 */
class FishPoolsUI extends UIBase{
    private main_group:eui.Group;
    private lb_money:eui.Label;
    private lb_count:eui.Label;
    private btn_up:BaseButton;
    // private img_up:eui.Image;
    // private btn_money:BaseButton;
    // private btn_count:BaseButton;
    private img_hook:eui.Image;
    private btn_shop:BaseButton;
    private btn_oneKey:eui.Image;
    private bubble_particle:particle.ParticleSystem;
    private dot_particle:particle.ParticleSystem;
    private onekey_group:eui.Group;
    private fish_bg:eui.Image;
    private customFilter;
    private count:number = 120;
    private pools_group:eui.Group;

    private fish_group1:eui.Image;
    private fish_group2:eui.Image;

    /**
     * 升级的组合
     */
    private group_up:eui.Group;
    private btn_left_back:BaseButton;
    private btn_1:BaseButton;
    private btn_2:BaseButton;
    private btn_3:BaseButton;
    private lb_poolCnt1:eui.Label;
    private lb_poolCnt2:eui.Label;
    private lb_add1:eui.Label;
    private lb_add2:eui.Label;
    
    constructor()
    {
        super('FishPoolsView');
    }

    public init()
    {
        this.width = GlobalManager.instance().curWidth();
		this.height = GlobalManager.instance().curHeight();
        let money = RoleCache.instance().getGoldLb();
        this.lb_money.text = money + '';
        this.fixIphoneX();
        this.addParticle();
        this.addAnimation();
        this.sendToSever();
        egret.setTimeout(()=>{
            this.addCustomFilter();
        },this, 500);
    }

    public getCurFishNum()
    {
        return this.pools_group.numChildren;
    }

    public initLevelUpGroup()
    {
        let fishCnt = RoleCache.instance().fishpondCnt;
        let fishAdd = RoleCache.instance().getFishpondRate();

        this.lb_poolCnt1.text = fishCnt + '';
        if(fishCnt == 30)
            this.lb_poolCnt2.text = '30';
        else
            this.lb_poolCnt2.text = fishCnt+1+'';

        this.lb_add1.text = (fishAdd * 100).toFixed(0) + '%';
        
        if(fishAdd == 1)
        {
            this.lb_add2.text = '100%';
        }
        else
        {
            let nextAdd = (fishAdd + 0.1) * 10;
            this.lb_add2.text = (nextAdd * 10).toFixed(0)  + '%';
        }
    }

    public sendToSever()
    {
        FishPoolsPrase.instance().getFish(this.initUI, this);
    }

    public initUI(data)
    {
        for(let v of data)
        {
            this.addFish(v);
        }
        this.updateFishCnt();
        this.initLevelUpGroup();
    }
    //屏幕适配x
    protected fixIphoneX()
    {
        if(GlobalManager.instance().isIphonex())
            this.main_group.top = Math.floor(GlobalManager.instance().curHeight()/34);
    }

    public addParticle()
    {
        this.bubble_particle = ParticleManager.instance().getParticle('img_bubble', 'bubble');
        this.addChildAt(this.bubble_particle, 1);
        this.bubble_particle.emitterX = this.width - this.bubble_particle.width >> 1;
        this.bubble_particle.emitterY = this.height - this.bubble_particle.height - 30;
        this.bubble_particle.start();

        this.dot_particle = ParticleManager.instance().getParticle('dot', 'gold');
        this.onekey_group.addChildAt(this.dot_particle, 10);
        this.dot_particle.emitterX = this.onekey_group.width - this.dot_particle.width >> 1;
        this.dot_particle.emitterY = 50;
        this.dot_particle.start();
    }

    public addAnimation()
    {
        EffectUtil.instance().rockEffect(this.img_hook);
    }

    //聚宝盆处理
    public cornucopiaHandle()
    {
        //视频
        let Success_call = function()
        {  
            let data = {
                hours:Math.floor(Math.random() * 3 + 1)
            }
            FishPoolsPrase.instance().getMoney(data);;
        };
        let Error_call = function()
        {  
            MessageUtil.tips('观看完整视频才能聚宝成功哦');
        };
        WeChatgGameManager.instance().showVideoAd(GameConst.adList.offline_benefit, Success_call, Error_call, this);
    }

    public addEvent()
    {
        this.img_hook.addEventListener(egret.TouchEvent.TOUCH_TAP, this.backHome, this);
        GameUtil.addEventListener(EventConst.RESOURCE_CHANGED,this.UpdateMoney, this);
        this.btn_shop.addTapHandler(this.OpenShop,this);
        this.fish_bg.addEventListener(egret.Event.ENTER_FRAME, this.update, this);
        this.btn_up.addTapHandler(this.openUpUI,this);
        GameUtil.addEventListener(EventConst.SHARE_SUCCESS, this.shareSuccess,this);
        this.btn_oneKey.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onekeyHandle, this);
        this.btn_left_back.addTapHandler(this.hideLevelGp, this);

        for(let i=1;i<4;i++)
        {
            this['btn_'+i].addTapHandler(this.levelUpHandle.bind(this, [i]), this);
        }
    }

    private levelUpHandle(data)
    {
        let type = data[0];
        switch(type)
        {
            case 1:
                let fishCnt = RoleCache.instance().fishpondCnt;
                if(fishCnt >= 30)
                    MessageUtil.tips('已达到上限');
                else
                    this.addFishpondCnt();
                break;    
            case 2:
                this.cornucopiaHandle();
                break;
            case 3:
                let fishAdd = RoleCache.instance().getFishpondRate();
                if(fishAdd == 1)
                    MessageUtil.tips('已达到上限');
                else
                    this.addFishpondAdd();
                break;
            default: 
                break;
        }
    }

    //鱼塘收益系数增加
    private addFishpondAdd()
    {
        let random = Math.random();
        if(!RoleCache.instance().reviewStatus && random > 0.5)
        {
            //分享
            SharePrase.instance().requestOneAdvertisement({type:ShareId.FishpondIncome});
        }
        else
        {
            //视频
            let self = this;
            let Success_call = function()
            {  
                FishPoolsPrase.instance().getIncome(self.initLevelUpGroup, self);
            };
            let Error_call = function()
            {  
                MessageUtil.tips('观看完整视频才能增加鱼塘容量哦');
            };
            WeChatgGameManager.instance().showVideoAd(GameConst.adList.offline_benefit, Success_call, Error_call, this);
        }
    }

    private hideLevelGp()
    {
        EffectUtil.instance().StopEffect(this.group_up);
        egret.Tween.get(this.group_up).to({
            x:-this.group_up.width
        },500, egret.Ease.backIn).set({
            visible:false
        });
    }

    private openUpUI()
    {
        EffectUtil.instance().StopEffect(this.group_up);
        this.group_up.visible = true;
        egret.Tween.get(this.group_up).to({
            x:0
        },500, egret.Ease.backOut);
    }

    private onekeyHandle()
    {
        let random = Math.random();
        if(this.getCurFishNum() <= 0)
        {
            MessageUtil.tips('池塘里面没有鱼哦~');
            return ;
        }
        if(!RoleCache.instance().reviewStatus && random > 0.5)
        {
            //分享
            SharePrase.instance().requestOneAdvertisement({type:ShareId.oneKeyHanle});
        }
        else
        {
            //视频
            let Success_call = function()
            {  
                let data = {
                    fish_id:'all'
                }
                FishPoolsPrase.instance().soleFish(data, this.soleAllFish, this);;
            };
            let Error_call = function()
            {  
                MessageUtil.tips('观看完整视频才能使用一键收益哦');
            };
            WeChatgGameManager.instance().showVideoAd(GameConst.adList.offline_benefit, Success_call, Error_call, this);
        }
    }

    private soleAllFish()
    {
        let fish_num = this.pools_group.numChildren;
        if(fish_num > 0)
        {
            for(let i=0;i < fish_num;i++)
            {
                let fish = this.pools_group.getChildAt(i) as SmallFish;
                if(fish)
                {
                    fish.AddIconEffect();
                    fish.remove();
                    i--;
                    fish_num--;
                }
            }
        }
        this.updateFishCnt();
    }

    //变更资源数据
	protected UpdateMoney()
	{
		let curMoney = this.lb_money.text;
		let money = RoleCache.instance().getGoldLb();
		EffectUtil.instance().NumChange(this.lb_money, parseInt(curMoney), money, 500);
	}

    public update()
    {
        if(this.customFilter)
        {
            if(this.count == 0)
            {
                this.customFilter.uniforms.time += 0.005;
                if (this.customFilter.uniforms.time >= 1) {
                    this.customFilter.uniforms.time = 0.0;
                    this.count = 120;
                    this.randomShowTips();
                }
            }
            else
            {
                this.count--;
            }
        }

        let fish_num = this.pools_group.numChildren;
        if(fish_num > 0)
        {
            for(let i=0;i < fish_num;i++)
            {
                let fish = this.pools_group.getChildAt(i) as SmallFish;
                let dir = fish.dir == DirType.left?-1:1;
                fish.x += dir * fish.getSpeed();
                if(fish.x < -200 || fish.x > this.pools_group.width)
                {
                    fish.changeFishDir();
                    fish.y = Math.random() * (this.pools_group.height - 50);
                    let scale = fish.y / this.pools_group.height;
                    fish.scaleX = fish.scaleY = scale < 0.4 ? 0.4 : scale;
                }
            }
        }
        let dir = this.fish_group1.scaleX;
        this.fish_group1.x -= dir * 2;
        if(this.fish_group1.x < -this.fish_group1.width || this.fish_group1.x > this.pools_group.width + this.fish_group1.width){
            this.fish_group1.scaleX *= -1;
        }
        dir = this.fish_group2.scaleX;
        this.fish_group2.x += dir * 2;
        if(this.fish_group2.x < -this.fish_group1.width || this.fish_group2.x > this.pools_group.width + this.fish_group1.width){
            this.fish_group2.scaleX *= -1;
        }
    }

    public addCustomFilter()
    {
        let vertexSrc =
            "attribute vec2 aVertexPosition;\n" +
            "attribute vec2 aTextureCoord;\n" +
            "attribute vec2 aColor;\n" +

            "uniform vec2 projectionVector;\n" +

            "varying vec2 vTextureCoord;\n" +
            "varying vec4 vColor;\n" +

            "const vec2 center = vec2(-1.0, 1.0);\n" +

            "void main(void) {\n" +
            "   gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n" +
            "   vTextureCoord = aTextureCoord;\n" +
            "   vColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n" +
            "}";

        let fragmentSrc = [
            "precision lowp float;\n" +
            "varying vec2 vTextureCoord;",
            "varying vec4 vColor;\n",
            "uniform sampler2D uSampler;",

            "uniform vec2 center;",
            "uniform vec3 params;", // 10.0, 0.8, 0.1"
            "uniform float time;",

            "void main()",
            "{",
            "vec2 uv = vTextureCoord.xy;",
            "vec2 texCoord = uv;",

            "float dist = distance(uv, center);",

            "if ( (dist <= (time + params.z)) && (dist >= (time - params.z)) )",
            "{",
            "float diff = (dist - time);",
            "float powDiff = 1.0 - pow(abs(diff*params.x), params.y);",

            "float diffTime = diff  * powDiff;",
            "vec2 diffUV = normalize(uv - center);",
            "texCoord = uv + (diffUV * diffTime);",
            "}",

            "gl_FragColor = texture2D(uSampler, texCoord);",
            "}"
        ].join("\n");

        this.customFilter = new egret.CustomFilter(
            vertexSrc,
            fragmentSrc,
            {
                center: { x: 0.5, y: 0.5 },
                params: { x: 10, y: 0.8, z: 0.1 },
                time: 0
            }
        );

        this.fish_bg.filters = [this.customFilter];
    }

    protected OpenShop()
    {
        let data = {
            isPop:true,
            effect:4
        }
        UIManager.instance().openUILogic(FishShopUI, data);
    }

    public randomShowTips()
    {
        let fish_num = this.pools_group.numChildren;
        if(fish_num > 0)
        {
            let index : number = Math.random() * fish_num << 0;
            let fish = this.pools_group.getChildAt(index) as SmallFish;
            fish.showTips();
        }
    }

    public addFish(data)
    {
        if(data)
        {
            let fish = new SmallFish(data);
            this.pools_group.addChild(fish);
            fish.x = Math.random() * this.pools_group.width;
            fish.y = Math.random() * (this.pools_group.height - 50);
            let scale = fish.y / this.pools_group.height;
            fish.scaleX = fish.scaleY = scale < 0.4 ? 0.4 : scale;
        }
    }

    public addFishToPool(data)
    {
        this.addFish(data);
        this.updateFishCnt();
    }

    public updateFishCnt()
    {
        let fishCnt = RoleCache.instance().fishpondCnt;
        this.lb_count.text = this.getCurFishNum() + ' / ' + fishCnt;
    }

    protected addFishpondCnt()
    {
        let random = Math.random();
        if(!RoleCache.instance().reviewStatus && random > 0.5)
        {
            //分享
            SharePrase.instance().requestOneAdvertisement({type:ShareId.addFishpondCnt});
        }
        else
        {
            //视频
            let Success_call = function()
            {  
                FishPoolsPrase.instance().addFishpondCnt();
            };
            let Error_call = function()
            {  
                MessageUtil.tips('观看完整视频才能增加鱼塘容量哦');
            };
            WeChatgGameManager.instance().showVideoAd(GameConst.adList.offline_benefit, Success_call, Error_call, this);
        }
    }

    public shareSuccess(e:BaseEvent)
    {
        let data = e.param;
        let type = data['type'];
       
        if(type == ShareId.addFishpondCnt)
        {
            //增加鱼塘容量
            FishPoolsPrase.instance().addFishpondCnt();
        }
        else if(type == ShareId.oneKeyHanle)
        {
            //一键收益
            let data = {
                    fish_id:'all'
                }
            FishPoolsPrase.instance().soleFish(data, this.soleAllFish, this);;
        }
        else if(type == ShareId.FishpondIncome)
        {
            //鱼塘收益系数
            FishPoolsPrase.instance().getIncome(this.initLevelUpGroup, this);
        }
    }

    protected backHome()
    {
        EffectUtil.instance().StopEffect(this.img_hook);
        this.img_hook.rotation = 0;
        egret.Tween.get(this.img_hook).to({
            y:this.img_hook.y + 15 
        },200).to({
            y:this.img_hook.y
        },200).call(()=>{
            this.remove(6);
        })
    }

    public removeEvent()
    {
        this.img_hook.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.backHome, this);
        this.btn_shop.removeTapHandler();
        this.fish_bg.removeEventListener(egret.Event.ENTER_FRAME, this.update, this);
        GameUtil.removeEventListener(EventConst.RESOURCE_CHANGED,this.UpdateMoney, this);
        GameUtil.removeEventListener(EventConst.SHARE_SUCCESS, this.shareSuccess,this);
        this.btn_oneKey.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onekeyHandle, this);
        this.btn_up.removeTapHandler();
        this.btn_left_back.removeTapHandler();
        for(let i=1;i<4;i++)
        {
            this['btn_'+i].removeTapHandler();
        }
    }

    public clear()
    {
        super.clear();
        // EffectUtil.instance().StopEffect(this.img_up);
        // EffectUtil.instance().StopEffect(this.btn_count);
        let logic:MainUI = UIManager.instance().getLogicByName(UIConst.MAIN_UI) as MainUI;
        if(logic)
        {
            logic.setFishIncome();
        }
        EffectUtil.instance().StopEffect(this.img_hook);

        this.bubble_particle.stop();
        this.bubble_particle = null;
        this.dot_particle.stop();
        this.dot_particle = null;
        this.fish_bg.filters = null;
        this.count = null;
        this.customFilter = null;
        
        for(let v of this.pools_group.$children)
        {
            let fish = v as SmallFish;
            fish.remove();
        }
    }
}